package com.ys.controller.api.hr;

import java.util.List;
import java.util.Map;

import com.ys.service.flow.YspTaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.hr.TwlStockBorrow;
import com.ys.entity.hr.TwlStockBorrowDetail;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.hr.TwlStockBorrowService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/twlStockBorrow")
public class ApiInterTwlStockBorrowController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<TwlStockBorrow> commonApiService;
	@Autowired
	private CommonApiService<TwlStockBorrowDetail> commonApiServiceDetail;
	@Autowired
	private TwlStockBorrowService twlStockBorrowService;

	@Autowired
	private YspTaskService yspTaskService;
	
	@RequiresPermissions("twlStockBorrow:view")
	@RequestMapping("/search")
	@ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TwlStockBorrowDetail cond){
		
		cond = setSeachSql(cond);
		cond.setOrderby("A.Id DESC");
		return commonApiServiceDetail.searchLay(cond);
	}
	
	/*
	 * 新增
	 */
	@RequestMapping("/add")
	@ResponseBody
	@RequiresPermissions("twlStockBorrow:add")
	public R add(String bid, String borrowUserId, String remark, String subData) {
		try {
			//修改
			return twlStockBorrowService.add(bid, borrowUserId, remark, subData, MenuId.TWL_StockBorrow);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/*
	 * 编辑
	 */
	@RequiresPermissions("twlStockBorrow:add")
	@PostMapping("/edit")
	@ResponseBody
	public R edit(String bid, String borrowUserId, String remark, String subData){
		try {
			return twlStockBorrowService.edit(bid, borrowUserId, remark, subData, MenuId.TWL_StockBorrow);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/**
	 * 流转通过
	 */
	@RequiresPermissions("twlStockBorrow:add")
	@PostMapping("/flowPass")
	@ResponseBody
	public R flowPass(Long id){
		
		TwlStockBorrow entity = new TwlStockBorrow().setId(id).queryFirst();
		try {
			return twlStockBorrowService.flowPass(entity.getBid(), ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions("twlStockBorrow:add")
	@PostMapping("/flowRefuse")
	@ResponseBody
	public R flowRefuse(Long id, String reason){
		
		TwlStockBorrow entity = new TwlStockBorrow().setId(id).queryFirst();
		try {
			return twlStockBorrowService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}


	/**
	 * 流转驳回
	 */
	@RequiresPermissions("twlStockBorrow:add")
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(Long id, String reason){

		TwlStockBorrow entity = new TwlStockBorrow().setId(id).queryFirst();
		try {
			return yspTaskService.flowRefuse(entity.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 删除
	 * @throws Exception 
	 */
	@PostMapping("/delete")
	@ResponseBody
	public R delete(Long id){
		
		try {
			return twlStockBorrowService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("操作失败，请联系客服");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("twlStockBorrow:export")
	@RequestMapping("/export")
	@ResponseBody
	public R export(@ModelAttribute TwlStockBorrowDetail cond) throws Exception{
		
		cond = setSeachSql(cond);
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
		
		List<YsCol> listField = new YsCol()
				.setMenuId(MenuId.TWL_StockBorrow)
				.setFrontShow(YsColEnum.FrontShow.SHOW.value)
				.setOrderby("A.SortNo asc")
				.queryList();
		
		
		ExportExcelUtils<TwlStockBorrow> util = new ExportExcelUtils<TwlStockBorrow>(new TwlStockBorrow());
		
		String toFilePath = util.exportExcel(listData, listField, "物料入库单");
		UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
		return R.ok(dto.getUrl());
	}

	/**
	 * 设置查询的cond的sql设置
	 * @param cond
	 * @return
	 */
	public TwlStockBorrowDetail setSeachSql(TwlStockBorrowDetail cond){
		
		cond.addLeftJoin("TWL_StockBorrow B ON B.Bid = A.BidStockBorrow")
			.addField("B.Bid bid")
			.addField("B.EffectStock effectStock")
			.addField("B.Remark remarkStockBorrow");
		
		cond.addLeftJoin("TS_UserChange B1 ON B1.Id = B.CreateChangeId")
			.addField("B1.UserId createUserId");
		
		cond.addLeftJoin("TS_UserChange B2 ON B2.Id = B.BorrowChangeId")
			.addField("B2.UserId borrowUserId")
			.addField("B2.DeptName borrowOrgName");
		
		cond.addLeftJoin("YS_ProcInst C ON C.Bid = B.Bid")
			.addField("C.UpdateTime auditTime");
		
		cond.addLeftJoin("TWL_Stock E ON E.Id = A.StockId")
			.addField("E.Num stockNum")
			.addField("E.StockInDay stockInDay")
			.addField("E.Remark stockRemark")
			.addField("DATEDIFF(DAY, E.StockInDay, getdate()) stockInDays")
			.addField("(SELECT ISNULL(SUM(AA.Num), 0) FROM TWL_StockBorrowDetail AA LEFT JOIN TWL_StockBorrow BB ON BB.Bid = AA.BidStockBorrow WHERE BB.EffectStock = 1 AND AA.StockId = E.Id) numBorrowed");
		
		cond.addLeftJoin("TB_CompanyInfo E1 on E1.Vid = E.CompanyVid")
			.addField("E1.Vid companyVid")
			.addField("E1.Vname companyVname");
		
		cond.addLeftJoin("TS_OrganizationInfo E2 on E2.Orgid = E.Orgid")
			.addField("E2.Orgid orgid")
			.addField("E2.OrgName orgName")
			.addField("E2.HeadUserId orgHeadUserId");
		
		cond.addLeftJoin("TWL_StockInDetail E3 ON E3.Id = E.StockInDetailId")
			.addField("E3.Img img")
			.addField("E3.Price price")
			.addField("E3.BidStockIn bidStockIn");
		
		cond.addLeftJoin("TB_Material F ON F.Code = E.MaterialCode")
			.addField("F.Code materialCode")
			.addField("F.Name materialName")
			.addField("F.Remark materialRemark");
		
		
		
		return  cond;
	}
}
